<template>
  <nav class="navbar">
    <div class="logo">
      <img src="@/assets/logo.png" alt="网站Logo" />
    </div>
    <ul class="nav-links">
      <li><router-link to="/">首页</router-link></li>
      <li><router-link to="/course-introduction">课程介绍</router-link></li>
      <li><router-link to="/team">教学团队</router-link></li>
      <li><router-link to="/knowledge-map">知识图谱</router-link></li>
      <li><router-link to="/ability-map">能力图谱</router-link></li>
      <!-- <li><router-link to="/question-map">问题图谱</router-link></li>
      <li><router-link to="/value-map">价值图谱</router-link></li> -->
      <li><router-link to="/qa">互动问答</router-link></li>
    </ul>

    <div class="search-login">
      <input 
        type="text" 
        placeholder=" 搜索" 
        class="search-bar"
        v-model="searchInput"
        @keyup.enter="handleSearchEnter"
      />

      <div v-if="isLoggedIn" class="user-profile" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
        <img :src="userAvatar" class="avatar" alt="用户头像" />
        <span style="color: white" class="username">{{ username }}</span> 
        <ul v-if="showDropdown" class="dropdown-menu">
          <li v-if="userRole === 'teacher'">
            <router-link class="dropdown-text" to="/teacher/teacherset">教师个人中心</router-link>
          </li>
          <li v-if="userRole === 'student'">
            <router-link class="dropdown-text" to="/student/studentset">学生个人中心</router-link>
          </li>
          <li @click="logout">退出登录</li>
        </ul>
      </div>

       <div v-else>
        <router-link to="/login" class="login-button">登录/注册</router-link> 
      </div>
    </div>
      <div 
        v-if="!showAIChat && !isPreviewMode" 
        class="ai-mini-icon" 
        @click="showAIChat = true">
        <img style="background-color:white;border-radius:10px;width:40px;height:40px;padding:10px" src="@/assets/picture/AI.png" alt="AI助手">
      </div>

      <div v-if="showAIChat && !isPreviewMode" class="ai-mask" @click.self="showAIChat = false"></div>
      <div v-if="showAIChat && !isPreviewMode" class="ai-chat-container">
      <div class="chat-container">
          <div class="status-indicator">
            <span class="online-dot"></span>
            <h3 class="assistant-title">游戏策划AI小助手</h3>
          </div>
          <div class="message-list">
            <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
              <div class="avatar">{{ msg.role === 'user' ? '👤' : '🤖' }}</div>
              <div class="bubble">{{ msg.text }}</div>
            </div>
            <div v-if="isTyping" class="message ai">
              <div class="avatar">🤖</div>
              <div class="bubble typing">{{ currentAIText }}<span class="cursor">|</span></div>
            </div>
          </div>
          <div class="input-area">
           <input 
              v-model="currentMessage" 
              @keyup.enter="sendMessage"
              placeholder="输入消息..." 
              :disabled="isWaitingResponse"
            />
            <button @click="sendMessage" :disabled="isWaitingResponse">发送</button>
          </div>
        </div>
    </div>
  </nav>
</template>


<script>
export default {
  name: 'NavBar',
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userRole: {
      type: String,
      default: ''
    },
    userAvatar: {
      type: String,
      default: 'https://via.placeholder.com/40'
    },
    username: {  // 新增：接收用户名
      type: String,
      default: ''
    }
  },
  computed: {
 isPreviewMode() {
    return (
      this.$route.path.includes('stupreview') ||
      this.$route.path.includes('knowledge-map') ||
      this.$route.path.includes('ability-map')
    );
  }
},
  data() {
    return {
      showDropdown: false,
      showAIChat: false,
      currentMessage: '',
      messages: [],
      isWaitingResponse: false,
      isTyping: false,
      currentAIText: '',
      typingTimer: null,
      abortController: null,
      typingSpeed: 30
    };
  },
  methods: {
    
     logout() {
        // 保留关键登录信息
        const rememberMe = localStorage.getItem('rememberMe');
        const savedPhone = localStorage.getItem('phone_num');
        const savedPassword = localStorage.getItem('password');

        // 清除用户会话数据
        ['id', 'token', 'username', 'userAvatar', 'userRole', 'lastLoginTime'].forEach(key => {
            localStorage.removeItem(key);
            sessionStorage.removeItem(key);
        });

        // 保持记住我状态和凭证
        if (rememberMe === 'true') {
            localStorage.setItem('rememberMe', 'true');
            localStorage.setItem('phone_num', savedPhone);
            localStorage.setItem('password', savedPassword);
        }

        this.$emit('logout');
        this.$router.push('/');
    },
     handleSearchEnter() {
       if (this.isPreviewMode) return;
    if (this.searchInput.trim()) {
      this.showAIChat = true;
      this.currentMessage = this.searchInput;  // 将搜索内容传递给AI输入框
      this.searchInput = '';  // 清空搜索框
      
      // 自动聚焦到AI输入框
      this.$nextTick(() => {
        const input = document.querySelector('.ai-chat-container input');
        if (input) input.focus();
      });
    }
  },
      async sendMessage() {
  if (!this.currentMessage?.trim() || this.isWaitingResponse) return;

  // 1. 添加用户消息
  this.messages.push({
    role: "user",
    text: this.currentMessage,  // 使用currentMessage
  });
  const userMessage = this.currentMessage;  // 使用currentMessage
  this.currentMessage = "";  // 清空currentMessage
  this.isWaitingResponse = true;

  // 2. 创建AbortController以便取消请求
  this.abortController = new AbortController();

  try {
    const appId = "YTk2ejbUc1TDsr0Q28WbpDBM3P6TtOdG";
    const secretKey = "VF9BaoswFxgbi1oA3cFLKIShRZg4mqgm";
    const response = await fetch(
      `https://agentapi.baidu.com/assistant/conversation?appId=${appId}&secretKey=${secretKey}`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message: {
            content: {
              type: "text",
              value: { showText: userMessage }  // 使用新API要求的参数结构
            }
          },
          source: "appAnsId",
          from: "openapi",
          openId: localStorage.getItem('id')
        }),
        signal: this.abortController.signal,
      }
    );

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        if (!response.body) {
          throw new Error("ReadableStream not supported in this browser");
        }

        // 3. 处理流式响应
        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");
        let fullText = "";
        let buffer = "";
        let reading = true;
        while (reading) {
          const { done, value } = await reader.read();
          reading = !done;

          if (value) {
            buffer += decoder.decode(value, { stream: true });

            // 处理可能的多行数据
            const lines = buffer.split(/\r\n|\n|\r/);
            buffer = lines.pop() || "";

            for (const line of lines) {
              if (line.startsWith("data:")) {
                try {
                  const jsonStr = line.substring(5).trim();
                  if (jsonStr) {
                    const data = JSON.parse(jsonStr);
                    const newText = this.extractAIText(data);
                    if (newText) {
                      fullText += newText;
                      this.playTypingEffect(newText);
                    }
                  }
                } catch (err) {
                  console.error("解析错误:", err);
                }
              }
            }
          }
        }
        if (buffer.trim()) {
          try {
            const data = JSON.parse(buffer.substring(5).trim());
            const newText = this.extractAIText(data);
            if (newText) {
              fullText += newText;
              this.playTypingEffect(newText);
            }
          } catch (err) {
            console.error("最终解析错误:", err);
          }
        }
        this.messages.push({
          role: "ai",
          text: fullText,
        });
      } catch (err) {
        if (err.name === "AbortError") {
          console.log("请求已被取消");
        } else {
          console.error("请求失败:", err);
          this.messages.push({
            role: "ai",
            text: "抱歉，AI暂时无法响应，请稍后再试。",
          });
        }
      } finally {
        this.isWaitingResponse = false;
        this.isTyping = false;
        this.currentAIText = "";
        clearInterval(this.typingTimer);
        this.abortController = null;
      }
    },
    // 打字机效果
    playTypingEffect(fullText) {
      this.isTyping = true;
      clearInterval(this.typingTimer);

      let i = 0;
      this.typingTimer = setInterval(() => {
        if (i < fullText.length) {
          this.currentAIText += fullText.charAt(i);
          i++;
        } else {
          clearInterval(this.typingTimer);
        }
      }, this.typingSpeed);
    },

    // 取消请求的方法
    cancelRequest() {
      if (this.abortController) {
        this.abortController.abort();
      }
    },

    // 从API响应中提取AI文本
    extractAIText(data) {
      let result = "";
      if (data?.data?.message?.content) {
        data.data.message.content.forEach(item => {
          if (item.data?.text) {
            result += item.data.text;
          }
        });
      }
      return result;
    },
  }
};
</script>


<style scoped>
.ai-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.3);
  z-index: 999;
}

/* 迷你AI图标 */
.ai-mini-icon {
  position: fixed;
  right: 40px;
  bottom: 40px;
  width: 40px;
  height: 40px;
  cursor: pointer;
  z-index: 1000;
  transition: transform 0.3s ease;
}

.ai-mini-icon:hover {
  transform: scale(1.1);
}

.ai-mini-icon img {
  width: 100%;
  height: 100%;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}

/* 调整原聊天容器层级 */
.ai-chat-container {
  overflow: hidden;
  z-index: 1000; /* 确保对话框在遮罩层之上 */
  /* 原有样式保持不变... */
}
.ai-chat-container {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 350px;
  height: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  display: flex;
  flex-direction: column;
  transform: translateY(100%);
  animation: slideUp 0.3s ease-out forwards;
}
.ai-chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}
.message.user { text-align: right; }
.message.ai { text-align: left; }
@keyframes slideUp {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}
.navbar {
  position: relative;
  z-index: 1000;
}

.dropdown-menu {
  width: auto; 
  border-radius: 5px;
}

.dropdown-menu li:hover .dropdown-text {
  color: white; /* 确保router-link文字变为白色 */
}
.dropdown-text{
  text-decoration: none;
  color: #8D8D8D;
}
.navbar {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px 20px;
  background-color: #083171;
}

.logo img {
  height: 60px;
  margin-right: -20px;
  margin-bottom: -10px;
}

.nav-links {
  list-style: none;
  display: flex;
  gap: 5px;
  margin-right: 250px;
}

.nav-links li {
  display: inline;
}

.nav-links a {
  color: #fff;
  text-decoration: none;
  padding: 10px;
  position: relative; /* 为伪元素或边框定位做准备 */
}


/* 当前激活链接显示下划线 */
.nav-links a.router-link-active {
  font-weight: bold;
  border-bottom: 3px solid #1abc9c;
}

.search-login {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-bar {
  padding: 5px;
  border-radius: 20px;
  border: 1px solid #ccc;
  margin-left: 60px;
}

.user-profile {
  position: relative;
  display: flex; /* 将头像和用户名并排显示 */
  align-items: center; /* 垂直居中 */
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
}

.username {
  margin-left: 10px; /* 添加间距 */
  color: #fff; /* 字体颜色 */
  font-size: 16px; /* 字体大小 */
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 30px;
  background-color: white;
  border: 1px solid #ccc;
  list-style: none;
  padding: 0;
  width: 130px;
  margin: 0;
}

.dropdown-menu li {
  width: 100px;
  margin: 10px;
  padding: 5px;
  text-align: center;
  color: #8d8d8d;
  font-weight: bold;
  border-radius: 5px;
  font-size: 15px;
}

.dropdown-menu li:hover {
  background-color: #093272;
  color: white;
  cursor: pointer;

}.login-button {
  color: white; /* 字体颜色为白色 */
  background-color: #72DDA5; /* 背景颜色为 #72DDA5 */
  border-radius: 20px; /* 两侧圆角 */
  padding: 4px 16px; /* 内边距，调整按钮大小 */
  text-decoration: none; /* 移除下划线 */
  display: inline-block; /* 使 padding 生效 */
  transition: transform 0.3s ease, background-color 0.3s ease; /* 添加过渡效果 */
}

.login-button:hover {
  transform: scale(1.05); /* 鼠标悬停时轻微放大 */
  background-color: #66c39e; /* 可选：悬停时稍微调整背景颜色以增强效果 */
  /* 您可以根据需要调整悬停时的背景颜色，或保持不变 */
}
/* AI聊天区域 */
.chat-container {
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  padding: 20px;
  height: 100%;
  position: relative; /* 新增定位上下文 */
}
/* 消息气泡 */
.bubble {
  padding: 12px 18px;
  border-radius: 15px;
  font-size: 14px;
  line-height: 1.5;
  max-width: 80%;
  transition: transform 0.2s;
}

.user .bubble {
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: #fff;
  border-radius: 15px 15px 4px 15px;
}

.ai .bubble {
  background: #3d3d3d;
  color:black;
  border-radius: 15px 15px 15px 4px;
}

/* 消息列表 */
.message-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
  padding-bottom: 80px;
}

.message-list::-webkit-scrollbar {
  width: 0;
  background: transparent;
}

.message {
  display: flex;
  margin-bottom: 12px;
}

.avatar {
  margin-right: 10px;
  font-size: 20px;
}

.bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 18px;
  line-height: 1.4;
}

.user {
  justify-content: flex-start;
  flex-direction: row-reverse;
}

.user .avatar {
  margin-left: 10px;
}

.ai {
  justify-content: flex-start;
}

.ai .bubble {
  background: white;
  border: 1px solid #eee;
}

.typing {
  position: relative;
}

.cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

.input-area {
  border-radius: 25px;
  padding: 8px 15px;
  margin-top: 15px;
  background: white;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  bottom: 40px;
  left: 40px;
}

.input-area input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  height: 30px;
}

.input-area button {
  margin-left: 8px;
  padding: 8px 16px;
  height: 40px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}
.status-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.online-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  background: #00ff00;
  border-radius: 50%;
  margin-right: 8px;
  animation: pulse 1.5s infinite;
  box-shadow: 0 0 8px rgba(0, 255, 0, 0.5);
}
.assistant-title {
  color: black;
  font-size: 16px;
  margin: 0;
}
</style>
